<?php

/**
* Script for creating and loading database
*/
 
// Initialize the application path and autoloading
$dirname = $_SERVER['PWD'];

defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath($dirname . '/../www/application'));

set_include_path(implode(PATH_SEPARATOR, array(
    APPLICATION_PATH . '/../www/library',
    get_include_path(),
)));

require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
Zend_Session::Start();
 
// Define some CLI options
$getopt = new Zend_Console_Getopt(array(
   'env|e-s'   => 'Application environment for which to create model s(defaults to development)',
   'help|h'    => 'Help -- usage message',
));

try
{
    $getopt->parse();
}
catch (Zend_Console_Getopt_Exception $e)
{
    // Bad options passed: report usage
    echo $e->getUsageMessage();
    return false;
}
 
// If help requested, report usage message
if ($getopt->getOption('h'))
{
    echo $getopt->getUsageMessage();
    return true;
}
 
// Initialize values based on presence or absence of CLI options
$env      = $getopt->getOption('e');
if($env === null)
   $env = get_current_user();
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (null === $env) ? 'development' : $env);
 
echo 'Using APPLICATION_ENV = ' . APPLICATION_ENV . PHP_EOL;

$tableName = $getopt->getOption('t');

// Initialize Zend_Application
$pApplication = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

$jsonStoreObj = array(
   'identifier' => 'uid',
   'label' => 'name',
   'items' => array()
);

$contentArray = array();
digestFolder(APPLICATION_PATH . '/../public/images/icons/', $jsonStoreObj, $contentArray);
file_put_contents(APPLICATION_PATH . '/../public/css/iconStore.js', Zend_Json::encode($jsonStoreObj));

// put css instructions into files
$i = 0;
$y = 1;
$cssInstructionIndex = 1;
$cssFileContent = '';
foreach($contentArray as $cssInstruction)
{
   $cssFileContent .= $cssInstruction;
   if($cssInstructionIndex % 4094 === 0 || $cssInstructionIndex >= count($contentArray))
   {
      // put the content into the file
      file_put_contents(APPLICATION_PATH . '/../public/css/spritesheet-'. str_pad($y++, 2, '0', STR_PAD_LEFT) .'.css', $cssFileContent);
      $cssFileContent = '';
   }
   $cssInstructionIndex++;
}

function digestFolder($path, & $jsonStoreObj, & $contentArray, $currentLevel = '')
{
   echo "Curent Level: " . $currentLevel. PHP_EOL;
   
   $jsonIconsArray = array();
   $files = listdir($path);
   sort($files, SORT_LOCALE_STRING);
   foreach($files as $file)
   {
      //echo $file . PHP_EOL;
      
      // Don't do hidden files - or ., .. dirrectories
      if(substr($file, 0, 1) == '.')
         continue;
      
      if(is_dir($path . $file))
      {
         digestFolder($path . $file . '/', $jsonStoreObj, $contentArray, $currentLevel . $file . '/');
         continue;
      }
      else if(!is_file($path . $file))
         continue;
      
      $strippedFile = substr($file, -4);
      if ($strippedFile != '.png')
         continue;
      
      $strippedFile = basename($file, '.png');

      $shortCssName = str_replace('/', '-', $currentLevel);
      

      list($width, $height, $type, $attr) = getimagesize($path . $file);
      
      $cssName = ".icons-$shortCssName$strippedFile";
      $cssPath = "/images/icons/$currentLevel$file";
      $uidPath = "icons/$currentLevel$file";
      
      $contentArray[] = "$cssName { width: ".$width."px; height: ".$height."px; background-image: url($cssPath) !important; background-repeat: no-repeat; }" . PHP_EOL;
      
      $jsonIconsArray[] = array(
         'name' => $strippedFile,
         'uid' => $uidPath,
         'type' => 'icon',
         'css' => $cssName,
         'width' => $width,
         'height' => $height,
         'path' => $cssPath);
   }
   if($currentLevel != '' && count($jsonIconsArray) > 0)
      $jsonStoreObj['items'][] = array(
         'name' => $currentLevel,
         'uid'  => $currentLevel,
         'type' => 'category',
         'children' => $jsonIconsArray);
}

// http://php.net/manual/en/function.readdir.php
// post: frasq at frasq dot org 01-Nov-2010 03:46
function listdir($dir='.') { 
    if (!is_dir($dir)) { 
        return false; 
    } 
    
    $files = array(); 
    listdiraux($dir, $files); 

    return $files; 
} 

function listdiraux($dir, &$files) { 
    $handle = opendir($dir); 
    while (($file = readdir($handle)) !== false) { 
        if ($file == '.' || $file == '..') { 
            continue; 
        } 
        $filepath = $dir == '.' ? $file : $dir . '/' . $file; 
        //if (is_link($filepath)) 
        //    continue; 
        $files[] = $file; 
    } 
    closedir($handle); 
} 
